package com.butterfly.hotkey.worker.framework.netty.handler;

import cn.hutool.core.collection.CollUtil;
import com.butterfly.hotkey.core.model.HotKeyModel;
import com.butterfly.hotkey.core.model.msg.HotKeyMsg;
import com.butterfly.hotkey.common.disruptor.event.QueueEvent;
import com.butterfly.hotkey.common.disruptor.publish.QueueEventPublisher;
import com.butterfly.hotkey.common.factory.CommonFactoryBean;
import com.butterfly.hotkey.common.netty.INettyMsgHandler;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collection;

import static com.butterfly.hotkey.core.constant.MsgTypeConst.REQUEST_NEW_KEY;
import static com.butterfly.hotkey.worker.constants.FactoryConstant.HANDLER;
import static com.butterfly.hotkey.worker.constants.TopicConst.TOPIC_NEW_KEY;

/**
 * 处理client端发送的所有key处理
 *
 * @author butterfly
 */
@Component
@CommonFactoryBean(type = HANDLER, valueInt = REQUEST_NEW_KEY)
public class HotKeyHandler implements INettyMsgHandler {

    @Resource
    private QueueEventPublisher queueEventPublisher;

    @Override
    public void handle(HotKeyMsg message, ChannelHandlerContext context) {
        Collection<HotKeyModel> hotKeyModels = message.getHotKeyModels();
        if (CollUtil.isEmpty(hotKeyModels)) {
            return;
        }
        // 直接循环发送到队列中
        for (HotKeyModel hotkey : hotKeyModels) {
            QueueEvent queueEvent = new QueueEvent();
            queueEvent.setData(hotkey);
            queueEventPublisher.publishEvent(TOPIC_NEW_KEY, queueEvent);
        }
    }
}
